import React from 'react'
import { connect } from 'react-redux'
import { Tabs, Select, Spin, Modal, Button, Tooltip } from 'antd'
const TabPane = Tabs.TabPane;
import 'styles/financial-management/finance-audit/audit.scss'
import { messages } from "share/common";
import { getWsUrl } from 'share/utils';
import financeAuditService from './finance-audit.service'
const Option = Select.Option;
import Condition from 'components/condition'
import openSlideFrame from "share/openSlideFrame";
const { If } = Condition;
import SlideExpenseReportDetail from './slide-expense-report-detail'
import FinanceAuditExpense from './finance-audit-expense'
import FinanceAuditBorrow from './finance-audit-borrow'
import FinanceAuditCorporate from './finance-audit-corporate'
import FinanceAuditMode from './finance-audit-mode'
import config from "config";
import ReconnectingWebSocket from "reconnectingwebsocket";
import AuditTipsBottomFrame from "./components/audit-tips/bottom-frame";

class FinanceAudit extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      tabKey: 'expense.prending_audit'
    };
  }

  connector = null;
  connectStatus = false;
  data = [];
  hasConfirm = false;

  componentDidMount() {
    if(this.connector) this.connector.close();
    !window.ISIE9 && this.openWebSocket();
  }

  openWebSocket = () => {
    let url = getWsUrl('/ws/scancode?scanMode=REVIEW');
    this.connector = new ReconnectingWebSocket(url);
    this.connector.onopen = this.onOpen;
    this.connector.onerror = this.onError;
    this.connector.onmessage = this.onMessage;
    this.connector.onclose = this.onClose;
  };

  onOpen = () => {
    const { loginUser: { userOID }, authToken: { access_token } } = this.props;
    let body = {
      userOID: userOID,
      token: access_token
    };
    let dict = {
      command: 'AUTH',
      body: JSON.stringify(body)
    };
    let dataSend = JSON.stringify(dict) + '\0';
    this.connector.send(dataSend);
  };

  onError = error => {
    this.connectStatus = false;
  };

  onMessage = msg => {
    this.data.push(JSON.parse(JSON.stringify(msg)).data);
    this.analyseData();
  };

  onClose = () => {
    if (this.connectStatus)
      this.connectStatus = false;
  };

  analyseData = () => {
    let lastReceive = this.data.pop();
    let end = '\0';
    if (lastReceive.indexOf(end) === -1) {
      this.data.push(lastReceive);
      return;
    }
    let temp = lastReceive.split(end);
    let expense = JSON.parse(this.data.join('') + temp[0]);
    if (temp[1] !== '') {
      this.data = [];
      this.data.push(temp[1]);
    }
    if (expense.command === 'ERROR') {
      if (this.hasConfirm)
        return;
      this.hasConfirm = true;
      Modal.confirm({
        title: 'Oops',
        content: expense.body,
        okText: messages('expense-14.key246')/*重连*/,
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.hasConfirm = false
        },
        onCancel: () => {
          this.hasConfirm = false;
          this.data = [];
          this.connector.close();
        }
      });
      return;
    }
    expense.body = JSON.parse(expense.body);
    if (!expense.body || !expense.body.type || !expense.body.content) return;
    if (expense.command !== 'MESSAGE') return;
    let content = expense.body.content.split(':');
    if ('AUTH_SUCCESS' === expense.body.type) {
      this.connectStatus = true;
    } else if ('BILL_REVIEW' === expense.body.type) {
      let url = '';
      if([5001, 1002].includes(+content[0])) {
        openSlideFrame.openExpenseReport({
          expenseReportOID: content[2],
          status: 'prending_audit',
          entry: 'audit',
          backType: 'history',
          activeTab: +content[5] === 1002 ? 'invoice' : '',
          billReviewMode: content[5]
        }, {
          content: SlideExpenseReportDetail,
          noPadding: true,
          afterClose: value => typeof value === 'boolean' && value && this.refreshList()
        }, this);
      }
      if(Number(content[0]) === 3001) {
        openSlideFrame.openLoanReport({
          formOID: content[1],
          loanBillOID: content[2],
          backType: 'history',
          status: 'prending_audit',
          billReviewMode: content[5],
          pathname: this.props.location.pathname,
          entry: 'audit',
        }, {
          afterClose: value => typeof value === 'boolean' && value && this.refreshList()
        }, this);
      }
    }
  };

  componentWillUnmount = () => {
    if(this.connector)
      this.connector.close();
  };

  refreshList = () => {
    const { tabKey } = this.state;
    this[tabKey] && this[tabKey].advancedTableRef && this[tabKey].advancedTableRef.getList();
  };

  render() {
    const { tabKey } = this.state;
    const { tenantInfo, language } = this.props;
    const sections = tabKey.split('.');
    const status = sections[1];
    return (
      <div className="finance-audit full-height-page new-finance-audit">
          <div className='finance-audit-container'>
            <Tabs tabBarExtraContent={<FinanceAuditMode/>} onChange={tabKey => this.setState({ tabKey })}>
              <TabPane tab={messages('expense-14.key240')/*【报销单】待审核*/} key="expense.prending_audit">
                <FinanceAuditExpense
                  status={status}
                  onRef={ref => this['expense.prending_audit'] = ref}
                  tenantInfo={tenantInfo}
                />
              </TabPane>
              <TabPane tab={messages('expense-14.key241')/*【报销单】已审核*/} key="expense.audit_pass">
                <FinanceAuditExpense
                  status={status}
                  onRef={ref => this['expense.audit_pass'] = ref}
                  tenantInfo={tenantInfo}
                />
              </TabPane>
              <TabPane tab={messages('expense-14.key235')/*【借款单】待审核*/} key="borrow.prending_audit">
                <FinanceAuditBorrow
                  status={status} pathname={this.props.location.pathname}
                  onRef={ref => this['borrow.prending_audit'] = ref}
                />
              </TabPane>
              <TabPane tab={messages('expense-14.key236')/*【借款单】已审核*/} key="borrow.audit_pass">
                <FinanceAuditBorrow
                  status={status} pathname={this.props.location.pathname}
                  onRef={ref => this['borrow.audit_pass'] = ref}
                />
              </TabPane>
              <TabPane tab={messages('expense-14.key506')/*【对公支付单】待审核*/} key="corporate.prending_audit">
                <FinanceAuditCorporate
                  status={status}
                  onRef={ref => this['corporate.prending_audit'] = ref}
                />
              </TabPane>
              <TabPane tab={messages('expense-14.key507')/*【对公支付单】已审核*/} key="corporate.audit_pass">
                <FinanceAuditCorporate
                  status={status}
                  onRef={ref => this['corporate.audit_pass'] = ref}
                />
              </TabPane>
            </Tabs>
            {language.code === 'zh_cn' &&  <AuditTipsBottomFrame from="auditList" />}
          </div>
      </div>
    )
  }

}

FinanceAudit.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    companyConfiguration: state.login.companyConfiguration,
    profile: state.login.profile,
    company: state.login.company,
    loginUser: state.login.loginUser,
    financeAudit: state.cache.financeAudit,
    authToken: state.main.authToken,
    tenantInfo: state.login.tenant,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(FinanceAudit);
